package com.gxc.datacore.ws.util;

import java.util.HashMap;
import java.util.Map;

import com.gxc.authcore.client.cache.AuthCacheClient;
import com.gxc.authcore.system.cache.UserCache;
import com.gxc.authcore.system.domain.User;
import com.gxc.authcore.system.util.AuthInfo;
import com.gxc.authcore.system.util.CurrentUtil;

public class UserAccessUtil {

	/**
	 * webservcie登陆用户缓存Map<user_id, authid>
	 */
	@SuppressWarnings("rawtypes")
	private static Map wsUserCache = new HashMap();

	/**
	 * 用户名密码校验，同时设置CurrentUtil中的authid和authCache，确保后续调用CurrentUtil时获取正确结果。
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	public static boolean checkPassword(String username, String password) {
		// 获取登录用户信息
		User user = UserCache.getUser(username);
		// 验证用户信息
		if (user == null) {
			return false;
		} else {
			// 验证密码
			String db_password = user.getPassword();
			if (db_password == null || !db_password.equals(password)) {
				return false;
			} else {
				String authid = (String) wsUserCache.get(username);
				AuthInfo authInfo = null;
				if (authid != null) {
					authInfo = AuthCacheClient.getAuthInfo(authid);
				}
				if (authInfo == null) {
					authInfo = AuthCacheClient.setAuthInfo(username);
					wsUserCache.put(username, authid);
				}
				CurrentUtil.setAuthid(authid);
				CurrentUtil.setAuthInfo(authInfo);
			}
			return true;
		}
	}
}
